package edu.neu.cs6515.xml;

import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.io.IOUtils;

/**
 * Used to read XML turn and turn it into a Java object
 */
public final class XMLTurnUnmarshaller {

    private final JAXBContext context;
    private final Unmarshaller unmarshaller;

    /**
     * Initalizes unmarshaller
     * 
     * @throws JAXBException
     *             if there's a problem initializing a JAXBContext
     */
    public XMLTurnUnmarshaller() throws JAXBException {
        context = JAXBContext.newInstance(XMLTurnProxy.class);
        unmarshaller = context.createUnmarshaller();
    }

    /**
     * Turns XML representation of a Turn into a corresponding Java object
     * 
     * @param input
     *            xml representation
     * @return new Turn object
     */
    public XMLTurnProxy unmarshall(final String input) throws JAXBException {
        final InputStream inputStream = IOUtils.toInputStream(input);
        Object objectFromXML = unmarshaller.unmarshal(inputStream);
        if (objectFromXML instanceof XMLTurnProxy) {
            return (XMLTurnProxy) objectFromXML;
        }
        throw new JAXBException("XML did not contain turn object!");
    }
}
